'use client';

import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Tag, 
  Button, 
  Space, 
  Modal, 
  Descriptions, 
  List,
  message,
  Input,
  Select,
  Row,
  Col,
  Statistic,
  Image
} from 'antd';
import { 
  EyeOutlined, 
  CloseOutlined,
  SearchOutlined,
  ShoppingCartOutlined,
  DollarCircleOutlined,
  FileTextOutlined
} from '@ant-design/icons';
import { useRouter } from 'next/navigation';
import { request } from '@/utils/request';
import { API_ENDPOINTS } from '@/utils/constants';

const { Option } = Select;

interface OrderItem {
  id: number;
  orderId: number;
  productId: number;
  productName: string;
  productImage: string;
  quantity: number;
  unitPrice: number;
  totalPrice: number;
  batchNumber?: string;
  specifications?: string;
  createdAt: string;
}

interface Order {
  id: number;
  userId: number;
  userName: string;
  orderNumber: string;
  totalAmount: number;
  shippingFee: number;
  discountAmount: number;
  finalAmount: number;
  status: string;
  paymentMethod?: string;
  paymentTime?: string;
  recipientName: string;
  recipientPhone: string;
  shippingAddress: string;
  logisticsCompany?: string;
  trackingNumber?: string;
  remark?: string;
  createdAt: string;
  updatedAt: string;
  orderItems: OrderItem[];
}

const UserOrders: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [orders, setOrders] = useState<Order[]>([]);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [orderStats, setOrderStats] = useState<any>({});
  const router = useRouter();

  useEffect(() => {
    checkUserAuth();
    fetchOrders();
    fetchOrderStats();
  }, [pagination.current, pagination.pageSize, statusFilter]);

  const checkUserAuth = () => {
    const token = localStorage.getItem('seafood_token');
    if (!token) {
      message.error('请先登录');
      router.push('/login');
      return;
    }
  };

  const fetchOrders = async () => {
    try {
      setLoading(true);
      
      const params = new URLSearchParams({
        page: pagination.current.toString(),
        size: pagination.pageSize.toString()
      });
      
      if (statusFilter) {
        params.append('status', statusFilter);
      }
      
      const response = await request.get(`${API_ENDPOINTS.ORDERS.LIST}/my?${params.toString()}`);
      
      if (response.code === 200) {
        setOrders(response.data.content || []);
        setPagination(prev => ({ 
          ...prev, 
          total: response.data.totalElements || 0 
        }));
      } else {
        message.error(response.message || '获取订单列表失败');
        if (response.code === 401) {
          router.push('/login');
        }
      }
    } catch (error: any) {
      message.error(error.message || '获取订单列表失败');
      if (error.message.includes('401')) {
        router.push('/login');
      }
    } finally {
      setLoading(false);
    }
  };

  const fetchOrderStats = async () => {
    try {
      // 调用后端统计接口获取真实数据
      const response = await request.get('/orders/stats/my');
      if (response.code === 200) {
        setOrderStats(response.data);
      } else {
        // 如果获取失败，使用默认值
        setOrderStats({
          totalOrders: 0,
          totalAmount: 0,
          pendingOrders: 0,
          completedOrders: 0
        });
      }
    } catch (error) {
      console.error('获取订单统计失败:', error);
      // 出错时使用默认值
      setOrderStats({
        totalOrders: 0,
        totalAmount: 0,
        pendingOrders: 0,
        completedOrders: 0
      });
    }
  };

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      'PENDING': 'orange',
      'PAID': 'blue',
      'SHIPPED': 'green',
      'DELIVERED': 'green',
      'CANCELLED': 'red'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status: string) => {
    const texts: Record<string, string> = {
      'PENDING': '待支付',
      'PAID': '已支付',
      'SHIPPED': '已发货',
      'DELIVERED': '已送达',
      'CANCELLED': '已取消'
    };
    return texts[status] || status;
  };

  const handleViewDetail = (order: Order) => {
    setSelectedOrder(order);
    setDetailVisible(true);
  };

  const handlePayOrder = async (order: Order) => {
    try {
      // 这里可以跳转到支付页面或打开支付模态框
      message.info('正在跳转到支付页面...');
      // 模拟支付跳转
      setTimeout(() => {
        message.success('支付成功！');
        // 重新获取订单列表以更新状态
        fetchOrders();
      }, 1000);
    } catch (error: any) {
      message.error(error.message || '支付失败');
    }
  };

  const handleCancelOrder = async (orderId: number) => {
    try {
      const response = await request.put(`${API_ENDPOINTS.ORDERS.CANCEL}/${orderId}/cancel`);
      
      if (response.code === 200) {
        message.success('订单取消成功');
        fetchOrders();
      } else {
        message.error(response.message || '取消订单失败');
      }
    } catch (error: any) {
      message.error(error.message || '取消订单失败');
    }
  };

  const handleSearch = () => {
    // 搜索功能可以在这里实现，暂时使用状态筛选
    fetchOrders();
  };

  const handleStatusChange = (value: string) => {
    setStatusFilter(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
      width: 200,
    },
    {
      title: '商品',
      dataIndex: 'orderItems',
      key: 'orderItems',
      width: 300,
      render: (items: OrderItem[]) => (
        <div>
          {items.slice(0, 2).map(item => (
            <div key={item.id} style={{ display: 'flex', alignItems: 'center', marginBottom: '4px' }}>
              <Image
                width={40}
                height={40}
                src={item.productImage}
                alt={item.productName}
                fallback="/images/default-product.png"
                style={{ marginRight: '8px', borderRadius: '4px' }}
              />
              <span>{item.productName} x{item.quantity}</span>
            </div>
          ))}
          {items.length > 2 && (
            <div style={{ color: '#666', fontSize: '12px' }}>
              等{items.length}件商品
            </div>
          )}
        </div>
      ),
    },
    {
      title: '金额',
      dataIndex: 'finalAmount',
      key: 'finalAmount',
      width: 120,
      render: (amount: number) => (
        <span style={{ color: '#f50', fontWeight: 'bold' }}>
          ¥{amount.toFixed(2)}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      ),
    },
    {
      title: '下单时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (text: any, record: Order) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small" 
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            查看详情
          </Button>
          {record.status === 'PENDING' && (
            <Button 
              type="primary" 
              size="small" 
              onClick={() => handlePayOrder(record)}
              style={{ marginRight: '8px' }}
            >
              立即支付
            </Button>
          )}
          {record.status === 'PENDING' && (
            <Button 
              type="link" 
              size="small" 
              danger
              icon={<CloseOutlined />}
              onClick={() => handleCancelOrder(record.id)}
            >
              取消订单
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div style={{ maxWidth: '1200px', margin: '0 auto', padding: '24px' }}>
      <h1 style={{ marginBottom: '24px', fontSize: '28px', fontWeight: 'bold' }}>
        我的订单
      </h1>

      {/* 订单统计 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="总订单数"
              value={orderStats.totalOrders || 0}
              prefix={<FileTextOutlined />}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="总消费金额"
              value={orderStats.totalAmount || 0}
              prefix={<DollarCircleOutlined />}
              precision={2}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="待支付订单"
              value={orderStats.pendingOrders || 0}
              prefix={<ShoppingCartOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="已完成订单"
              value={orderStats.completedOrders || 0}
              prefix={<ShoppingCartOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索筛选 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row gutter={[16, 16]} align="middle">
          <Col xs={24} sm={8}>
            <Input
              placeholder="搜索订单号或商品名称"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onPressEnter={handleSearch}
            />
          </Col>
          <Col xs={24} sm={6}>
            <Select
              placeholder="订单状态"
              value={statusFilter}
              onChange={handleStatusChange}
              style={{ width: '100%' }}
              allowClear
            >
              <Option value="">全部状态</Option>
              <Option value="PENDING">待支付</Option>
              <Option value="PAID">已支付</Option>
              <Option value="SHIPPED">已发货</Option>
              <Option value="DELIVERED">已送达</Option>
              <Option value="CANCELLED">已取消</Option>
            </Select>
          </Col>
          <Col xs={24} sm={4}>
            <Button 
              type="primary" 
              icon={<SearchOutlined />}
              onClick={handleSearch}
              style={{ width: '100%' }}
            >
              搜索
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 订单列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({
                ...prev,
                current: page,
                pageSize: pageSize || prev.pageSize,
              }));
            },
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 订单详情模态框 */}
      <Modal
        title="订单详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={800}
      >
        {selectedOrder && (
          <div>
            <Descriptions bordered column={2} style={{ marginBottom: '24px' }}>
              <Descriptions.Item label="订单号" span={2}>
                {selectedOrder.orderNumber}
              </Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={getStatusColor(selectedOrder.status)}>
                  {getStatusText(selectedOrder.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="下单时间">
                {selectedOrder.createdAt}
              </Descriptions.Item>
              <Descriptions.Item label="支付方式">
                {selectedOrder.paymentMethod || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="支付时间">
                {selectedOrder.paymentTime || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="收货人">
                {selectedOrder.recipientName}
              </Descriptions.Item>
              <Descriptions.Item label="联系电话">
                {selectedOrder.recipientPhone}
              </Descriptions.Item>
              <Descriptions.Item label="收货地址" span={2}>
                {selectedOrder.shippingAddress}
              </Descriptions.Item>
              {selectedOrder.logisticsCompany && (
                <>
                  <Descriptions.Item label="物流公司">
                    {selectedOrder.logisticsCompany}
                  </Descriptions.Item>
                  <Descriptions.Item label="物流单号">
                    {selectedOrder.trackingNumber}
                  </Descriptions.Item>
                </>
              )}
              <Descriptions.Item label="商品总额">
                ¥{selectedOrder.totalAmount.toFixed(2)}
              </Descriptions.Item>
              <Descriptions.Item label="实付金额">
                <span style={{ color: '#f50', fontWeight: 'bold' }}>
                  ¥{selectedOrder.finalAmount.toFixed(2)}
                </span>
              </Descriptions.Item>
            </Descriptions>

            <h3 style={{ marginBottom: '16px' }}>商品清单</h3>
            <List
              dataSource={selectedOrder.orderItems}
              renderItem={(item: OrderItem) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Image
                        width={60}
                        height={60}
                        src={item.productImage}
                        alt={item.productName}
                        fallback="/images/default-product.png"
                        style={{ borderRadius: '4px' }}
                      />
                    }
                    title={item.productName}
                    description={
                      <div>
                        <div>单价: ¥{item.unitPrice.toFixed(2)}</div>
                        <div>数量: {item.quantity}</div>
                        <div style={{ color: '#f50', fontWeight: 'bold' }}>
                          小计: ¥{item.totalPrice.toFixed(2)}
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </div>
        )}
      </Modal>
    </div>
  );
};

export default UserOrders;